var Tasklog=Tasklog||{}

Tasklog.airWin=(function(Tasklog){ return {
	saveTimeout:null, bounds:null, file: null, stream: null, prefsXML: null
	
	,init: function(){
		var self=this;
		window.nativeWindow.addEventListener(air.Event.CLOSING, function(e){ self.onClose.call(self,e) })
		this.readPrefs();
	}
	
	,onClose: function(e){
		e.preventDefault();
		nativeWindow.removeEventListener(air.Event.CLOSING, this.onClose)
		this.savePrefs();
		air.NativeApplication.nativeApplication.exit();
	}	
	
	,openFile: function(mode){
		//var appF = air.File.applicationDirectory; // put prefs in app dir - flash sec. err
		//var appF = air.File.applicationStorageDirectory; // put prefs in app storage
		var appF = air.File.documentsDirectory; // put prefs in my docs
		this.file = appF.resolvePath("tasklog-preferences.xml");
		this.stream = new air.FileStream();
		if (mode=='READ' && !this.file.exists) return false; // no prefs
		this.stream.open(this.file, air.FileMode[mode]);
		return true;
	}
	
	,createXML: function(){
		var cr = air.File.lineEnding;
		var w=window.outerWidth, h=window.outerHeight, x=window.screenLeft, y=window.screenTop;
		this.prefsXML = '<?xml version="1.0" encoding="utf-8"?>'+cr
							+ '<preferences>'+cr 
								+ '<windowState width="'+w+'" height="'+h+'" x="'+x+'" y="'+y+'"/>'+cr
							+ '</preferences>';
		return this.prefsXML;
	}

	,savePrefs: function(){
		if (this.openFile('WRITE')){
			this.stream.writeUTFBytes(this.createXML());
			this.stream.close();
		}
	}
	
	,readPrefs: function(){
		if (this.openFile('READ')){
			this.prefsXML = this.stream.readUTFBytes(this.stream.bytesAvailable);
			this.stream.close();
			var domParser = new DOMParser();
			this.prefsXML = domParser.parseFromString(this.prefsXML, "text/xml");
			var windowState = this.prefsXML.getElementsByTagName("windowState")[0];
			window.moveTo(windowState.getAttribute("x"), windowState.getAttribute("y"));
			window.resizeTo(windowState.getAttribute("width"), windowState.getAttribute("height"));
		}
		window.nativeWindow.visible = true;
	}
	
}}(Tasklog));
Tasklog.airWin.init();




function doPrintAir(){
	var pjob = new window.runtime.flash.printing.PrintJob;
	pjob.jobName='Tasklog';
	if (pjob.start()){
		var poptions = new window.runtime.flash.printing.PrintJobOptions;
		poptions.printAsBitmap = true;
		try{ pjob.addPage(window.htmlLoader, null, poptions); pjob.send(); }
		catch(e){ die("exception: " + e); }
	}
	else die('PrintJob couldn\'t start');
}
window.print = doPrintAir; //comment the line below if you do not want to mess with existing window.print


